import React, { useState } from 'react';
import { 
  Card, 
  Button, 
  Space, 
  message, 
  Row, 
  Col, 
  Input, 
  Form, 
  Select, 
  Radio, 
  DatePicker,
  Table,
  Tag,
  Divider
} from '@/utils/antd-imports';
import employeeApi from '@/api/employeeApi';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

const EmployeeApiTest = () => {
  const [loading, setLoading] = useState(false);
  const [testResults, setTestResults] = useState({});
  const [employeeList, setEmployeeList] = useState([]);
  const [form] = Form.useForm();

  // 测试员工列表查询
  const testEmployeeList = async () => {
    setLoading(true);
    try {
      const response = await employeeApi.getEmployeeList({
        page: 1,
        size: 10,
        status: 1
      });
      
      console.log('员工列表响应:', response);
      
      if (response.code === 200) {
        setEmployeeList(response.data?.records || []);
        setTestResults(prev => ({
          ...prev,
          employeeList: {
            success: true,
            data: response.data,
            message: `查询成功，共 ${response.data?.total || 0} 条记录`
          }
        }));
        message.success(`员工列表查询成功，共 ${response.data?.total || 0} 条记录`);
      } else {
        throw new Error(response.message || '查询失败');
      }
    } catch (error) {
      console.error('员工列表查询失败:', error);
      setTestResults(prev => ({
        ...prev,
        employeeList: {
          success: false,
          error: error.message || '查询失败'
        }
      }));
      message.error(`员工列表查询失败: ${error.message || '请重试'}`);
    } finally {
      setLoading(false);
    }
  };

  // 测试创建员工
  const testCreateEmployee = async (values) => {
    setLoading(true);
    try {
      const employeeData = {
        employeeType: values.employeeType || '正式',
        name: values.name || '测试员工',
        gender: values.gender || '男',
        maritalStatus: values.maritalStatus || '未婚',
        nativePlace: values.nativePlace || '测试籍贯',
        politicalStatus: values.politicalStatus || '群众',
        birthday: values.birthday ? dayjs(values.birthday).format('YYYY-MM-DD') : '1990-01-01',
        idCard: values.idCard || '110101199001011234',
        registeredAddress: values.registeredAddress || '测试户籍地址',
        phone: values.phone || '13800138000',
        wechat: values.wechat || 'test_wechat',
        email: values.email || 'test@example.com',
        education: values.education || '本科',
        major: values.major || '计算机科学',
        graduationDate: values.graduationDate ? dayjs(values.graduationDate).format('YYYY-MM-DD') : '2012-06-01',
        emergencyContact: values.emergencyContact || '紧急联系人',
        emergencyPhone: values.emergencyPhone || '13900139000',
        bankAccount: values.bankAccount || '6222021234567890123',
        bankName: values.bankName || '中国银行',
        currentAddress: values.currentAddress || '测试现住址',
        ethnicity: values.ethnicity || '汉族',
        skillCertificates: values.skillCertificates || '测试证书',
        remarks: 'API测试创建'
      };

      console.log('创建员工请求数据:', employeeData);
      
      const response = await employeeApi.createEmployee(employeeData);
      
      console.log('创建员工响应:', response);
      
      setTestResults(prev => ({
        ...prev,
        createEmployee: {
          success: true,
          data: response,
          message: '员工创建成功'
        }
      }));
      
      message.success('员工创建成功');
      form.resetFields();
      
      // 刷新员工列表
      testEmployeeList();
      
    } catch (error) {
      console.error('创建员工失败:', error);
      setTestResults(prev => ({
        ...prev,
        createEmployee: {
          success: false,
          error: error.message || '创建失败'
        }
      }));
      message.error(`创建员工失败: ${error.message || '请重试'}`);
    } finally {
      setLoading(false);
    }
  };

  // 测试根据状态查询员工
  const testEmployeesByStatus = async (status) => {
    setLoading(true);
    try {
      const response = await employeeApi.getEmployeesByStatus(status);
      
      console.log(`状态${status}员工查询响应:`, response);
      
      if (response.code === 200) {
        setTestResults(prev => ({
          ...prev,
          employeesByStatus: {
            success: true,
            data: response.data,
            message: `状态${status}员工查询成功，共 ${response.data?.length || 0} 条记录`
          }
        }));
        message.success(`状态${status}员工查询成功，共 ${response.data?.length || 0} 条记录`);
      } else {
        throw new Error(response.message || '查询失败');
      }
    } catch (error) {
      console.error(`状态${status}员工查询失败:`, error);
      setTestResults(prev => ({
        ...prev,
        employeesByStatus: {
          success: false,
          error: error.message || '查询失败'
        }
      }));
      message.error(`状态${status}员工查询失败: ${error.message || '请重试'}`);
    } finally {
      setLoading(false);
    }
  };

  // 测试根据身份证查询员工
  const testEmployeeByIdCard = async (idCard) => {
    if (!idCard) {
      message.error('请输入身份证号');
      return;
    }
    
    setLoading(true);
    try {
      const response = await employeeApi.getEmployeeByIdCard(idCard);
      
      console.log('身份证查询员工响应:', response);
      
      if (response.code === 200) {
        setTestResults(prev => ({
          ...prev,
          employeeByIdCard: {
            success: true,
            data: response.data,
            message: '身份证查询员工成功'
          }
        }));
        message.success('身份证查询员工成功');
      } else {
        throw new Error(response.message || '查询失败');
      }
    } catch (error) {
      console.error('身份证查询员工失败:', error);
      setTestResults(prev => ({
        ...prev,
        employeeByIdCard: {
          success: false,
          error: error.message || '查询失败'
        }
      }));
      message.error(`身份证查询员工失败: ${error.message || '请重试'}`);
    } finally {
      setLoading(false);
    }
  };

  // 员工列表表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '员工类型',
      dataIndex: 'employeeType',
      key: 'employeeType',
      width: 100,
      render: (type) => (
        <Tag color={type === '正式' ? 'green' : type === '实习' ? 'blue' : 'orange'}>
          {type}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '在职' : '离职'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <h1>员工API测试页面</h1>
      
      <Row gutter={16}>
        {/* 员工列表查询测试 */}
        <Col span={12}>
          <Card title="员工列表查询测试" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <strong>当前员工数量:</strong> {employeeList.length}
              </div>
              <Button 
                type="primary" 
                onClick={testEmployeeList}
                loading={loading}
                block
              >
                测试员工列表查询
              </Button>
              {testResults.employeeList && (
                <div style={{ 
                  padding: '8px', 
                  backgroundColor: testResults.employeeList.success ? '#f6ffed' : '#fff2f0',
                  border: `1px solid ${testResults.employeeList.success ? '#b7eb8f' : '#ffccc7'}`,
                  borderRadius: '6px'
                }}>
                  <strong>结果:</strong> {testResults.employeeList.message || testResults.employeeList.error}
                </div>
              )}
            </Space>
          </Card>
        </Col>

        {/* 状态查询测试 */}
        <Col span={12}>
          <Card title="按状态查询员工测试" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Space>
                <Button 
                  onClick={() => testEmployeesByStatus(1)}
                  loading={loading}
                >
                  查询在职员工
                </Button>
                <Button 
                  onClick={() => testEmployeesByStatus(0)}
                  loading={loading}
                >
                  查询离职员工
                </Button>
              </Space>
              {testResults.employeesByStatus && (
                <div style={{ 
                  padding: '8px', 
                  backgroundColor: testResults.employeesByStatus.success ? '#f6ffed' : '#fff2f0',
                  border: `1px solid ${testResults.employeesByStatus.success ? '#b7eb8f' : '#ffccc7'}`,
                  borderRadius: '6px'
                }}>
                  <strong>结果:</strong> {testResults.employeesByStatus.message || testResults.employeesByStatus.error}
                </div>
              )}
            </Space>
          </Card>
        </Col>
      </Row>

      {/* 身份证查询测试 */}
      <Card title="身份证查询员工测试" style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Space>
            <Input
              placeholder="请输入身份证号"
              style={{ width: 200 }}
              onPressEnter={(e) => testEmployeeByIdCard(e.target.value)}
            />
            <Button 
              type="primary"
              onClick={() => testEmployeeByIdCard(document.querySelector('input[placeholder="请输入身份证号"]').value)}
              loading={loading}
            >
              查询员工
            </Button>
          </Space>
          {testResults.employeeByIdCard && (
            <div style={{ 
              padding: '8px', 
              backgroundColor: testResults.employeeByIdCard.success ? '#f6ffed' : '#fff2f0',
              border: `1px solid ${testResults.employeeByIdCard.success ? '#b7eb8f' : '#ffccc7'}`,
              borderRadius: '6px'
            }}>
              <strong>结果:</strong> {testResults.employeeByIdCard.message || testResults.employeeByIdCard.error}
            </div>
          )}
        </Space>
      </Card>

      {/* 创建员工测试 */}
      <Card title="创建员工测试" style={{ marginBottom: 16 }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={testCreateEmployee}
          style={{ maxWidth: 600 }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="性别"
                name="gender"
                rules={[{ required: true, message: '请选择性别' }]}
              >
                <Radio.Group>
                  <Radio value="男">男</Radio>
                  <Radio value="女">女</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="身份证号"
                name="idCard"
                rules={[
                  { required: true, message: '请输入身份证号' },
                  { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[0-9Xx]$/, message: '请输入正确的身份证号码' }
                ]}
              >
                <Input placeholder="请输入身份证号" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="员工类型"
                name="employeeType"
                rules={[{ required: true, message: '请选择员工类型' }]}
              >
                <Select placeholder="请选择员工类型">
                  <Option value="正式">正式</Option>
                  <Option value="实习">实习</Option>
                  <Option value="见习">见习</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="学历"
                name="education"
                rules={[{ required: true, message: '请选择学历' }]}
              >
                <Select placeholder="请选择学历">
                  <Option value="高中">高中</Option>
                  <Option value="大专">大专</Option>
                  <Option value="本科">本科</Option>
                  <Option value="硕士">硕士</Option>
                  <Option value="博士">博士</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              block
            >
              测试创建员工
            </Button>
          </Form.Item>
        </Form>

        {testResults.createEmployee && (
          <div style={{ 
            padding: '8px', 
            backgroundColor: testResults.createEmployee.success ? '#f6ffed' : '#fff2f0',
            border: `1px solid ${testResults.createEmployee.success ? '#b7eb8f' : '#ffccc7'}`,
            borderRadius: '6px',
            marginTop: '16px'
          }}>
            <strong>结果:</strong> {testResults.createEmployee.message || testResults.createEmployee.error}
          </div>
        )}
      </Card>

      {/* 员工列表显示 */}
      {employeeList.length > 0 && (
        <Card title="员工列表数据">
          <Table
            columns={columns}
            dataSource={employeeList}
            rowKey="id"
            pagination={false}
            size="small"
            scroll={{ x: 800 }}
          />
        </Card>
      )}

      <Divider />
      
      <Card title="API测试说明">
        <div style={{ fontSize: '14px', lineHeight: '1.6' }}>
          <p><strong>测试功能包括：</strong></p>
          <ul>
            <li>员工列表分页查询</li>
            <li>按状态查询员工（在职/离职）</li>
            <li>根据身份证号查询员工</li>
            <li>创建新员工</li>
          </ul>
          <p><strong>注意事项：</strong></p>
          <ul>
            <li>请确保后端API服务正常运行在 http://localhost:8087</li>
            <li>测试数据会真实提交到数据库，请谨慎操作</li>
            <li>查看浏览器控制台可获取详细的请求和响应信息</li>
          </ul>
        </div>
      </Card>
    </div>
  );
};

export default EmployeeApiTest;
